package com.midea.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
AtomicInteger 类主要利用 CAS (compare and swap) + volatile 和 native 方法来保证原子操作，从而避免 synchronized 的高开销，执行效率大为提升。
*/
public class TestAtomicInteger {

    private static volatile int a = 0;
    private static AtomicInteger b = new AtomicInteger(0);
    private static Integer c = Integer.valueOf(0);
    private static MyObject obj = new MyObject();
    private static int d = 0;
    private static AtomicInteger f = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        TestAtomicInteger testAtomicInteger = new TestAtomicInteger();
        Thread[] threads = new Thread[5];
        for (int i = 0;i < 5;i++){
            /**
             * Lambda表达式用法
             * threads[i] = new Thread(new Runnable() {
            @Override
            public void run() {
            System.out.println("");
            }
            });*/
            threads[i] = new Thread(() -> {
                try{
                    for (int j = 0;j < 1000;j++){
                        a++;
                        b.incrementAndGet();
                        //b.getAndIncrement();
                        //Thread.sleep(500);
                        synchronized (c){
                            c = Integer.valueOf(c.intValue()+1);
                        }
                        synchronized (obj){
                            obj.x++;
                        }
                        synchronized (TestAtomicInteger.class){
                            d++;
                        }
                        //每次加2
                        f.getAndAdd(2);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            });
            threads[i].start();
        }

        for (int i = 0;i < 5;i++){
            threads[i].join();
        }
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(obj.x);
        System.out.println(d);
        System.out.println(f);
    }
}


class MyObject{
    public int x = 0;
}
